﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Configuration;
using System.Web.UI;
using System.Web.Caching;
using System.Threading;
using BarberShop.Common.Enum;
namespace Maticsoft.Common
{
    #region class UploadUtil
    public class UploadUtil
    {
        private Stream reader;
        private FileStream fStream;
        private const int BUFFERSIZE = 10000;
        private string filePath;
        private Page page;
        private string guid;
        public UploadUtil(Page page, string guid,MultimediaType filetype)
        {
            this.page = page;
            this.guid = guid;
            this.filePath = new Page().Server.MapPath(ConfigurationManager.AppSettings[filetype.ToString()]);
        }
        public bool Upload(out DownloadingFileInfo fileinfo)
        {
            if (this.page.Request.Files.Count > 0)
            {
                return this.doUpload(this.page.Request.Files[0],out fileinfo);
            }
            else
            {
                fileinfo = null;
                return false;
            }
        }
        private bool doUpload(HttpPostedFile postedFile,out DownloadingFileInfo info)
        {
            bool _abort = false;

            try
            {
                //string _filePath = this.filePath + DateTime.Now.ToFileTime() + "\\";
                string _filePath = this.filePath;
                if (!Directory.Exists(_filePath))
                {
                    Directory.CreateDirectory(_filePath);
                }
                int flag = -1;

                //解决ie诡异问题
                flag = postedFile.FileName.LastIndexOf("\\");

                string _fileName = flag == -1 ? postedFile.FileName : postedFile.FileName.Substring(flag + 1, postedFile.FileName.Length - flag - 1);
                string _lastfileName = mikecat_GetNumberRandom() + _fileName.Substring(_fileName.IndexOf('.'), +_fileName.Length - _fileName.IndexOf('.'));

                //DownloadingFileInfo info = 
                info=new DownloadingFileInfo(_fileName,_lastfileName, postedFile.ContentLength, postedFile.ContentType);
                object fileObj = HttpContext.Current.Cache[this.guid];
                if (fileObj != null)
                {
                    HttpContext.Current.Cache.Remove(this.guid);
                }
                HttpContext.Current.Cache.Add(this.guid, info, null, DateTime.Now.AddDays(1), TimeSpan.Zero, CacheItemPriority.AboveNormal, null);
                DateTime begin = DateTime.Now.ToLocalTime();
                fStream = new FileStream(_filePath + _lastfileName, FileMode.Create);
                reader = postedFile.InputStream;
                byte[] buffer = new byte[BUFFERSIZE];
                int len = reader.Read(buffer, 0, BUFFERSIZE);

                while (len > 0 && !_abort)
                {
                    fStream.Write(buffer, 0, len);
                    DateTime end = DateTime.Now.ToLocalTime();
                    info.CostTime = (long)(end - begin).TotalMilliseconds;
                    info.FileFinished += len;

                    //模拟延时用，实际应用的时候注销他
                    //Thread.Sleep(10);

                    HttpContext.Current.Cache[this.guid] = info;
                    _abort = ((DownloadingFileInfo)HttpContext.Current.Cache[this.guid]).Abort;
                    len = reader.Read(buffer, 0, BUFFERSIZE);
                }

                reader.Close();
                fStream.Close();
                if (_abort)
                {
                    if (File.Exists(_filePath + _fileName))
                    {
                        File.Delete(_filePath + _fileName);
                    }
                }
                return true;
            }
            catch {
                info = null;
                return false; }
        }


        /// <summary>
        /// 获得数字形式的随机字符串
        /// </summary>
        /// <returns>数字形式的随机字符串</returns>
        public static string mikecat_GetNumberRandom()
        {
            int mikecat_intNum;
            long mikecat_lngNum;
            string mikecat_strNum = System.DateTime.Now.ToString().Replace("/","").Replace("AM","").Replace("PM","");
            mikecat_strNum = mikecat_strNum.Replace(":", "");
            mikecat_strNum = mikecat_strNum.Replace("-", "");
            mikecat_strNum = mikecat_strNum.Replace(" ", "");
            mikecat_lngNum = long.Parse(mikecat_strNum);
            System.Random mikecat_ran = new Random();
            mikecat_intNum = mikecat_ran.Next(1, 99999);
            mikecat_ran = null;
            mikecat_lngNum += mikecat_intNum;
            return mikecat_lngNum.ToString();
        }

    }
    #endregion

    #region class DownloadingFileInfo
    public class DownloadingFileInfo
    {
        public DownloadingFileInfo(string fileName,string lastfileName, Int64 fileSize, string fileType)
        {
            this.fileName = fileName;
            this.lastfileName = lastfileName;
            this.fileSize = fileSize;
            this.fileType = fileType;
            this.FileState = "开始上传";
        }

        private double speed;

        public double Speed
        {
            get
            {
                speed = costTime == 0 ? 0 : fileFinished / costTime;
                return speed;
            }

        }

        private string fileType;

        public string FileType
        {
            get { return fileType; }

        }

        /// <summary>
        /// 原始文件名
        /// </summary>
        private string fileName;

        public string FileName
        {
            get { return fileName; }

        }

        /// <summary>
        /// 上传后生成的文件名
        /// </summary>
        private string lastfileName;

        public string LastFileName
        {
            get { return lastfileName; }

        }

        private double fileSize;

        public double FileSize
        {
            get { return fileSize; }

        }
        private double fileFinished;

        public double FileFinished
        {
            get { return fileFinished; }
            set { fileFinished = value; }
        }
        private double costTime;

        public double CostTime
        {
            get { return costTime; }
            set { costTime = value; }
        }
        private string fileState;

        public string FileState
        {
            get
            {
                if (fileFinished == 0)
                {
                    fileState = "preparing";
                }
                else if (fileFinished > 0 && fileFinished < fileSize)
                {
                    fileState = "uploading";
                }
                else
                {
                    fileState = "finished";
                }
                return fileState;

            }
            set { fileState = value; }
        }

        private double percent;

        public double Percent
        {
            get
            {
                percent = fileFinished / fileSize;
                return percent;
            }

        }

        private bool abort = false;

        public bool Abort
        {
            get { return abort; }
            set { abort = value; }
        }
    }
    #endregion
}